<!--
 * @Author: quit
 * @Date: 2021-11-17 09:25:19
 * @LastEditTime: 2021-12-21 17:43:44
 * @Descripttion: 通讯设备
-->
<template>
  <div id="CommunicationsDevices">
    <div class="app-container">
      <el-card>
        <el-row class="row1">
          <el-divider content-position="left">{{ $t('divider.divider1') }}</el-divider>
          <div class="search">
            <el-form :inline="true" :model="formInline">
              <el-form-item :label="'设备名称'">
                <el-input v-model="formInline.name" :placeholder="'请输入设备名称'" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-zoom-in" @click="getDeviceList">{{ $t('button.search') }}</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-refresh-right" @click="refresh">{{ '重置' }}</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-row>
        <el-row>
          <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addItemBtn">{{ $t('button.addItems') }}</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="batchRemove">{{ $t('button.batchRemove') }}</el-button>
        </el-row>
        <el-row>
          <el-table
            ref="table"
            v-loading="loading"
            :max-height="maxHeight"
            :data="tableData"
            :empty-text="$t('table.emptyText')"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" min-width="40" fixed="left" />
            <el-table-column prop="dlldrid" label="ID" width="50" fixed="left" />
            <el-table-column prop="dlldrname" :label="'设备名'" min-width="120" fixed="left" />
            <el-table-column prop="dradd" :label="'设备地址'" min-width="100" />
            <el-table-column prop="type" :label="'类型'" min-width="100" />
            <el-table-column prop="dllid" :label="'驱动'" min-width="100" />
            <el-table-column prop="com" :label="'串口'" min-width="100" />
            <el-table-column prop="baudrate" :label="'波特率'" min-width="100" />
            <el-table-column prop="databits" :label="'数据位'" min-width="100" />
            <el-table-column prop="stopbits" :label="'停止位'" min-width="100" />
            <el-table-column prop="paritys" :label="'校验'" min-width="100" />
            <el-table-column prop="cjtimeout" :label="'超时时间'" min-width="100" />
            <el-table-column prop="macid" :label="'采集编号'" min-width="100" />
            <el-table-column header-align="center" align="center" fixed="right" :label="$t('table.operable')" width="200">
              <template slot-scope="scope">
                <el-button type="warning" size="mini" @click="handleEdit(scope.row)">{{ $t('button.edit') }}</el-button>
                <el-button type="danger" size="mini" @click="handleDelete(scope.row)">{{ $t('button.delete') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <!-- 分页 -->
            <el-pagination
              :current-page="pages.page"
              :page-sizes="[1, 5, 10, 15]"
              :page-size="pages.size"
              layout="prev, pager, next, total, sizes, jumper"
              :total="pages.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-row>
      </el-card>
    </div>
    <!-- 添加\编辑弹出框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" @close="handleClose">
      <el-form :model="dialogForm" class="dialog-form" label-width="90px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="设备名">
              <el-input v-model="dialogForm.dlldrname" placeholder="请填写设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型">
              <el-select v-model="dialogForm.type" clearable placeholder="请选择设备类型">
                <el-option v-for="(item, index) in typeData" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="23">
            <el-form-item label="设备地址">
              <el-input v-model="dialogForm.dradd" placeholder="此项填写设备地址IP带端口号（IP:502）" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="驱动ID">
              <el-select v-model="dialogForm.dllid" clearable placeholder="请选择驱动类型">
                <el-option v-for="(item, index) in dllidData" :key="index" :label="item.dllname" :value="item.dllid" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="dialogForm.type === 1">
          <el-col :span="8">
            <el-form-item label="串口">
              <el-select v-model="dialogForm.com" clearable placeholder="请选择串口类型">
                <el-option v-for="(item, index) in comData" :key="index" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="波特率">
              <el-select v-model="dialogForm.baudrate" clearable placeholder="请选择波特率类型">
                <el-option v-for="(item, index) in baudrateData" :key="index" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数据位">
              <el-select v-model="dialogForm.databits" clearable placeholder="请选择数据位">
                <el-option v-for="(item, index) in databitsData" :key="index" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="dialogForm.type === 1">
          <el-col :span="8">
            <el-form-item label="停止位">
              <el-select v-model="dialogForm.stopbits" clearable placeholder="请选择停止位">
                <el-option v-for="(item, index) in stopbitsData" :key="index" :label="item.label" :value="item.label" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="校验">
              <el-select v-model="dialogForm.paritys" clearable placeholder="请选择校验类型">
                <el-option v-for="(item, index) in paritysData" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="超时时间">
              <el-input v-model="dialogForm.cjtimeout" placeholder="请填写超时时间" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="恢复时间">
              <el-input v-model="dialogForm.cjrecoverytime" placeholder="请填写恢复时间" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采集器编号">
              <el-input v-model="dialogForm.macid" placeholder="请填写采集器编号" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="dialogState === 0" type="primary" @click="sendAddItem">确 定</el-button>
        <el-button v-if="dialogState === 1" type="primary" @click="snedEditItme">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import $ from 'jquery'
import { getDeviceList, getDllList, addDeviceItem, editDeviceItem, deleteDevice } from '@/api/BmRequest'

export default {
  components: {},
  data() {
    return {
      formInline: { name: null },
      loading: false,
      maxHeight: null,
      tableData: [],
      checkedArr: [],
      pages: { page: 1, size: 10, total: 0 },
      dialogTitle: null,
      dialogState: null,
      dialogVisible: false,
      dialogForm: {
        dlldrid: null,
        dlldrname: null,
        dradd: null,
        type: null,
        dllid: null,
        com: null,
        baudrate: null,
        databits: null,
        stopbits: null,
        paritys: null,
        openstate: null,
        cjtimeout: null,
        cjrecoverytime: null,
        txstate: null,
        macid: null
      },
      typeData: [
        { label: '网络', value: 0 },
        { label: '串口', value: 1 }
      ],
      dllidData: [],
      comData: [{ label: 'COM1' }, { label: 'COM2' }, { label: 'COM3' }, { label: 'COM4' }, { label: 'COM5' }, { label: 'COM6' }, { label: 'COM7' }],
      baudrateData: [{ label: '2400' }, { label: '4800' }, { label: '9600' }],
      databitsData: [{ label: '7' }, { label: '8' }],
      stopbitsData: [{ label: '1' }, { label: '2' }],
      paritysData: [
        { label: '无校验', value: 0 },
        { label: '奇校验', value: 1 },
        { label: '偶校验', value: 2 }
      ]
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  created() {
    this.getDeviceList()
    this.getDllList()
  }, // 生命周期 - 创建完成（可以访问当前this实例）
  mounted() {
    this.setTableHeight()
    window.onresize = () => {
      this.setTableHeight()
    }
  }, // 生命周期 - 挂载完成（可以访问DOM元素）
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
  // 方法集合
  methods: {
    // 动态设置表格高
    setTableHeight() {
      let num = $('.right-container').height() - 203
      this.maxHeight = num
    },
    async getDllList() {
      const { data } = await getDllList()
      this.dllidData = data
    },

    // 获取当前table数据
    async getDeviceList() {
      this.loading = true
      const obj = {
        dlldrmanager: { dlldrname: this.formInline.name },
        pages: { page: this.pages.page, size: this.pages.size }
      }
      try {
        const { data } = await getDeviceList(obj)
        this.tableData = data.records
        this.pages.page = data.current
        this.pages.size = data.size
        this.pages.total = data.total
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },

    // 重置
    refresh() {
      this.formInline = { name: null }
      this.pages = { page: 1, size: 10 }
      this.getDeviceList()
    },

    // 添加按钮
    addItemBtn() {
      this.dialogTitle = '添加通讯设备信息'
      this.dialogState = 0
      this.dialogVisible = true
    },

    // 批量删除
    batchRemove() {
      if (this.checkedArr.length > 0) {
        this.$confirm('此操作将删除所选项, 是否继续?', '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            if (this.checkedArr.length === this.tableData.length) {
              if (this.pages.page > 1) {
                this.pages.page--
              } else {
                this.pages.page = 1
              }
            }
            const { message } = await deleteDevice(this.checkedArr)
            await this.getDeviceList()
            this.$message.success({ message })
          })
          .catch(error => {
            console.log(error)
            this.$refs.table.clearSelection()
          })
      } else {
        this.$message.warning('请选择需要删除的项目')
      }
    },

    // 表格多选事件
    async handleSelectionChange(val) {
      const arr = []
      val.forEach((item, i) => {
        arr.push(item.dlldrid)
      })
      this.checkedArr = arr
    },

    /* table-item 操作 */
    // 编辑按钮
    handleEdit(data) {
      this.dialogForm = { ...data }
      this.dialogTitle = '编辑通讯设备信息'
      this.dialogState = 1
      this.dialogVisible = true
    },
    // 删除
    handleDelete(data) {
      this.$confirm('此操作将删除当前项目, 是否继续?', '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const nowArr = [data.dlldrid]
          const { message } = await deleteDevice(nowArr)
          if (this.tableData.length === 1) {
            if (this.pages.page > 1) {
              this.pages.page--
            } else {
              this.pages.page = 1
            }
          }
          await this.getDeviceList()
          this.$message.success({ message })
        })
        .catch(error => {
          console.log(error)
        })
    },

    /* 弹出框事件 */
    // 关闭
    handleClose() {
      this.$refs.dialogForm.clearValidate()
    },
    // 确定
    async sendAddItem() {
      try {
        const { message } = await addDeviceItem(this.dialogForm)
        this.$message.success(message)
      } catch (error) {
        console.log(error)
      } finally {
        this.dialogVisible = false
        this.getDeviceList()
      }
    },
    // 提交
    async snedEditItme() {
      try {
        const { message } = await editDeviceItem(this.dialogForm)
        this.$message.success(message)
      } catch (error) {
        console.log(error)
      } finally {
        this.dialogVisible = false
        this.getDeviceList()
      }
    },

    /* 分页操作 */
    // 分页当前页切换
    async handleCurrentChange(newPage) {
      this.pages.page = newPage
      await this.getDeviceList()
    },
    // 分页显示条数切换
    async handleSizeChange(newSize) {
      this.pages.size = newSize
      await this.getDeviceList()
    }
  }
}
</script>

<style scoped>
.el-table {
  margin-top: 10px;
}
.el-form {
  margin-left: 20px;
}
.el-input {
  width: 300px;
}
</style>

<style lang="scss" scoped>
.row1 {
  margin-bottom: 10px;
  .search {
    border: 1px solid #dcdfe6;
    border-top: none;
    padding: 34px 10px 10px 10px;
    margin-top: -14px;
  }
}
.dialog-form {
  margin: 0;
  .el-input,
  .el-select,
  .el-textarea,
  .el-cascader {
    width: calc(100% - 10px);
  }
}
</style>
